package com.fitness.front.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;

/**
 * 密码加解密
 */
public class EncryptUtil {

    public static final String PASSWORD_SALT = "0123456789abcABC#def$DEF";

    /**
     * 密码sha1散列
     * @param originPassword
     * @param salt
     * @return
     */
    public static String encryptPassword(String originPassword,String salt){
        return DigestUtil.sha1Hex(getSpecialPrefix()+originPassword+salt);
    }

    private static String getSpecialPrefix(){
        return PASSWORD_SALT.substring(3,6)+PASSWORD_SALT.substring(7,12)+PASSWORD_SALT.substring(17);
    }

    /**
     * 校验密码是否匹配
     * @param originPass
     * @param salt
     * @param encodePassword
     * @return
     */
    public static boolean matchPassword(String originPass,String salt,String encodePassword){
        return encodePassword.equals(DigestUtil.sha1Hex(getSpecialPrefix()+originPass+salt));
    }

    public static String genRandomSalt(){
        int maxLength = PASSWORD_SALT.length() - 1;
        int minPos = RandomUtil.randomInt(0,maxLength,false,false);
        int maxPos = RandomUtil.randomInt(0,maxLength,false,false);
        int tmp = Math.max(minPos,maxPos);
        minPos = Math.min(minPos,maxPos);
        maxPos = tmp;

        return System.currentTimeMillis() + PASSWORD_SALT.substring(minPos,maxPos);
    }

}
